package com.kwan.xframe.mvp.presenter;

import androidx.annotation.CallSuper;
import android.util.Log;

import com.kwan.xframe.mvp.model.BaseModel;
import com.kwan.xframe.rxbus.RxBusManager;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashMap;

import io.reactivex.functions.Consumer;

/**
 * Presenter 基类
 * Created by Mr.Kwan on 2016-9-30.
 */

public abstract class BasePresenter implements IBasePresenter {

	protected IBaseView mIBaseView;
	private RxBusManager busManager;
	protected BaseModel mBaseModel;

	public BasePresenter(IBaseView iView) {
		mIBaseView = iView;
		busManager = new RxBusManager();
		mBaseModel = getBaseModel();
	}

	protected abstract BaseModel getBaseModel();

	public <T> void regRxBus(String eventName, Class<T> type, Consumer<T> next) {
		busManager.on(eventName, type, next);
	}

	public void postRxBus(Object tag, Object content) {
		busManager.post(tag, content);
	}

	@CallSuper
	public void onActivityCreate() {

	}

	@CallSuper
	public void onActivityResume() {

	}

	@CallSuper
	public void onActivityPause() {

	}

	@CallSuper
	public void onActivityDestroy() {


		Log.e("kwan", "Presenter onActivityDestroy:" + mIBaseView);

		busManager.clear();
		//要去取消掉model的请求
		if (mBaseModel != null)
			mBaseModel.clearDisposable();
		mBaseModel = null;
	}

	@Override
	public void onNoNetWork() {
		mIBaseView.toastMsg("当前没有网络！");
	}

	@Override
	public void onDataSuccess(int vocational_id, HashMap<String, Object> exData, Object data) {
		Log.e("BasePresenter", "onServerSuccess");
	}

	@Override
	public void onDataError(int vocational_id, HashMap exdata, Throwable throwable) {
		if (throwable instanceof SocketTimeoutException) {
			mIBaseView.toastMsg("连接超时,请稍后重试！");
		} else if (throwable instanceof ConnectException) {
			mIBaseView.toastMsg("网络连接异常，请检查您的网络状态！");
		} else if (throwable instanceof UnknownHostException) {
			mIBaseView.toastMsg("网络异常，UnknownHostException！");
		} else {
			mIBaseView.toastMsg(throwable.getMessage());
		}
		throwable.printStackTrace();
		Log.e("onServerError", throwable.getMessage());
		mIBaseView.dismissProgress();
	}

}
